﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace Async_await.DAL
{
    public abstract class DAL<T> : IDAL<T> where T : class
    {

        public DAL(DbContext db)
        {
            DB = db;
        }


        #region Properies
        /// <summary>
        /// 静态上下文
        /// </summary>
        //  protected readonly static DbContext DB = new Entity.testEntities();

        /// <summary>
        /// 实例上下文
        /// </summary>
        protected DbContext DB;

        #endregion
        #region IDAL<T> 成员

        public IQueryable<T> GetModel()
        {
            return DB.Set<T>();
        }

        public T GetEntity()
        {
            throw new NotImplementedException();
        }

        public virtual void Insert(T entity)
        {
            DB.Entry<T>(entity);
            DB.Set<T>().Add(entity);
            DB.SaveChanges();
        }

        public virtual void Update(T entity)
        {
            DB.Set<T>().Attach(entity);
            DB.Entry(entity).State = EntityState.Modified;
            DB.SaveChanges();

        }

        public virtual void Delete(T entity)
        {
            DB.Set<T>().Attach(entity);
            DB.Set<T>().Remove(entity);
            DB.SaveChanges();
        }

        #endregion
    }
}